/*
 * Copyright (c) 2020 Carnegie Lee
 * All rights reserved
 */
package com.geekc.threadpool.config;

import com.geekc.threadpool.pool.DefaultThreadPoolFactory;
import com.geekc.threadpool.pool.ThreadPool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.concurrent.CountDownLatch;

/**
 * 线程池配置类
 * @author Carnegie Lee
 */
@Configuration
@EnableConfigurationProperties(ThreadPoolConfigurationProperties.class)
public class ThreadPoolConfig {

    @Autowired
    public ThreadPoolConfigurationProperties properties;

    private CountDownLatch countDownLatch = new CountDownLatch(1);

    /**
     * 此处可以通过ThreadPool中的构造器，读取配置类进行设置
     * @see ThreadPoolConfigurationProperties
     * @return
     */
    @Bean
    public ThreadPool threadPool() {
        ThreadPool threadPool = DefaultThreadPoolFactory.getInstance();
        threadPool.build();
        return threadPool;
    }

    @PostConstruct
    public void start() {
        new Thread(() -> {
            try {
                countDownLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }

    @PreDestroy
    public void stop() {
        countDownLatch.countDown();
    }
}
